package com.play.ballen.mall.ui

import android.os.Bundle
import android.widget.Button
import androidx.recyclerview.widget.GridLayoutManager
import com.hjq.toast.ToastUtils
import com.play.ballen.R
import com.play.ballen.databinding.FragmentMallSaleBinding
import com.play.ballen.mall.adapter.MallBallAdapter
import com.play.ballen.mall.dialog.MallBuyDialogUtils
import com.play.ballen.mall.entity.MallBallInfo
import com.play.ballen.mall.entity.MallBallLevel
import com.play.ballen.mall.vm.MallVM
import com.play.ballen.me.dialog.InputPayPwdDialogUtils
import com.play.ballen.me.dialog.OperateSuccessDialogUtils
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.yuven.appframework.widget.SpacesItemDecoration
import com.yuven.baselib.component.BaseMVVMFragment
import com.yuven.baselib.utils.Logger
import com.yuven.baselib.utils.ResourceUtil
import com.yuven.baselib.utils.ViewUtils
import com.yuven.baselib.widget.MultiStateView

class MallSaleFragment : BaseMVVMFragment<MallVM, FragmentMallSaleBinding>() {

    private var isVisibleToUser = false    //是否可见
    private var isPrepared = false //布局是否准备好

    private val adapter: MallBallAdapter by lazy {
        MallBallAdapter(arrayListOf())
    }
    private var curEntity: MallBallInfo? = null

    private var needReload = false  //是否需要重新加载布局
    private var type = ""

    var levelCallBack: ((items: List<MallBallLevel>?) -> Unit)? = null
    var getSelectLevelId: (() -> String)? = null

    private val inputPayPwdDialogUtils by lazy {
        InputPayPwdDialogUtils(mContext)
    }

    private val operateSuccessDialogUtils by lazy { OperateSuccessDialogUtils(mContext) }
    private val mallBuyDialogUtils by lazy {
        MallBuyDialogUtils(mContext).apply {
            numberCallback = { count ->
                val map = mutableMapOf<String, Any>()
                map["id"] = curEntity!!.id
                map["num"] = count
                map["__token__"] = viewModel.rateInfo.value!!.__token__

                inputPayPwdDialogUtils.show { pwd ->
                    map["pay_password"] = pwd
                    viewModel.basketballBuy(true, map)
                }
            }
        }
    }

    companion object {
        val TAG: String = MallSaleFragment::class.java.simpleName

        fun newInstance(type: String): MallSaleFragment {
            val args = Bundle().apply {
                putString("type", type)
            }
            val fragment = MallSaleFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            type = it.getString("type", "")
        }
    }

    override fun initIntent() {}

    override fun layoutId(): Int {
        return R.layout.fragment_mall_sale
    }

    override fun viewModelClass(): Class<MallVM> {
        return MallVM::class.java
    }

    override fun initObserver() {
        super.initObserver()

        viewModel.actionGetBallFailure.observe(this) {
            dataBinding.refreshLayout.finishRefresh()
            dataBinding.refreshLayout.finishLoadMore()
            if (viewModel.page == 1) {
                dataBinding.msvLayout.viewState = MultiStateView.VIEW_STATE_ERROR
            } else {
                ToastUtils.show(ResourceUtil.getString(R.string.load_fail))
            }
        }

        viewModel.listBall.observe(this) {
            dataBinding.refreshLayout.finishRefresh()
            dataBinding.refreshLayout.finishLoadMore()

            if (!it.isNullOrEmpty()) {
                if (viewModel.page == 1) {
                    adapter.setList(it)
                    dataBinding.rv.scrollToPosition(0)
                    dataBinding.msvLayout.viewState = MultiStateView.VIEW_STATE_CONTENT
                } else {
                    adapter.addData(it)
                }
                viewModel.page++
            } else {
                //no data
                if (viewModel.page == 1) {
                    dataBinding.msvLayout.viewState = MultiStateView.VIEW_STATE_EMPTY
                } else {
                    ToastUtils.show(ResourceUtil.getString(R.string.load_end))
                }
            }
        }

        viewModel.listMallBallLevel.observe(this) {
            Logger.i("MallSaleFragment.levelCallBack = $levelCallBack")
            levelCallBack?.invoke(it)
        }

        viewModel.actionBuySuccess.observe(this) {
            operateSuccessDialogUtils.show(ResourceUtil.getString(R.string.mall_buy_success))
            //购买成功后刷新数据
            notifyLevelChange()
        }

        viewModel.rateInfo.observe(this) {
            it?.run {
                mallBuyDialogUtils.show(curEntity!!.price.toFloat(), rate)
            }
        }
    }

    override fun initView() {
        isPrepared = true

        dataBinding.msvLayout.findViewById<Button>(R.id.btnTryAgain).setOnClickListener {
            dataBinding.msvLayout.viewState = MultiStateView.VIEW_STATE_LOADING
            viewModel.basketballIndex(type, getSelectLevelId?.invoke())
        }
    }

    override fun initData() {
        dataBinding.refreshLayout.setEnableLoadMore(true)
        dataBinding.refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                viewModel.page = 1
                viewModel.basketballIndex(type, getSelectLevelId?.invoke())

            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                viewModel.basketballIndex(type, getSelectLevelId?.invoke())
            }
        })

        dataBinding.rv.layoutManager = GridLayoutManager(mContext, 2)
        dataBinding.rv.addItemDecoration(SpacesItemDecoration(2, ViewUtils.dip2px(10f), true))
        dataBinding.rv.adapter = adapter
        adapter.type = type
        adapter.addChildClickViewIds(R.id.btnBuy)
        adapter.setOnItemChildClickListener { a, view, position ->
            curEntity = adapter.data[position]
            if (type == MallFragment.TYPE_MALL_OFFICIAL) {
                viewModel.basketballBuyRate()
            } else {    //用户出售的篮球无需输入数量
                val map = mutableMapOf<String, Any>()
                map["id"] = curEntity!!.id
                map["num"] = 1
                viewModel.basketballBuy(false, map)
            }
        }

        loadData()
    }

    private fun loadData() {
        if (isVisibleToUser) {
            if (isPrepared || needReload) {
                dataBinding.msvLayout.viewState = MultiStateView.VIEW_STATE_LOADING
                viewModel.page = 1
                viewModel.basketballIndex(type, getSelectLevelId?.invoke())

                needReload = false
            }
        }
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        this.isVisibleToUser = isVisibleToUser
        if (isVisibleToUser) {
            loadData()
        } else {
            isPrepared = false
        }
    }

    fun notifyLevelChange() {
        needReload = true

        if (isVisibleToUser) {
            loadData()
        }
    }

}